package com.zzyl.nursing.service.impl;

import java.util.*;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.dto.UserLoginDto;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.LoginUserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 老人家属Service业务层处理
 *
 * @author ruoyi
 * @date 2025-05-23
 */
@Service
@Slf4j
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {

    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Autowired
    private WechatService wechatService;

    @Autowired
    private static List<String> NICK_NAMES_LIST = Arrays.asList(
            "钱途无量",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝");

    @Autowired
    private TokenService tokenService;

    /**
     * 登录
     *
     * @param dto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public LoginUserVo login(UserLoginDto dto) {

        log.info("1.前端调用微信wx.log()获取的openId和临时凭证码");
        String openId = wechatService.getOpenId(dto.getCode());
        if (StringUtils.isBlank(openId)) {
            throw new BaseException("获取openId失败");
        }

        log.info("2.根据openId查询用户数据（数据库中）");
        FamilyMember one = this.lambdaQuery().eq(FamilyMember::getOpenId, openId).one();
        if (ObjectUtil.isEmpty(one)) {
            log.info("3.如果用户不存在，则新增用户");
            // 随机生成昵称
            Collections.shuffle(NICK_NAMES_LIST);
            String nickName = NICK_NAMES_LIST.get(0) + RandomUtil.randomNumbers(4);
            one = FamilyMember.builder().name(nickName).openId(openId).build();
            // 保存到数据库中
            this.save(one);
        }

        log.info("4.判断用户的手机号是否存在，在调用微信接口来获取手机号");
        String userPhone = one.getPhone();
        if (StringUtils.isBlank(userPhone)) {
            String phone = wechatService.getPhone(dto.getPhoneCode());
            if (StringUtils.isBlank(phone)) {
                throw new BaseException("获取手机号失败");
            }
            log.info("5.得到手机号后完成用户表的更新");
            this.lambdaUpdate().eq(FamilyMember::getId, one.getId()).set(FamilyMember::getPhone, phone).update();
        }

        log.info("6. 生成登录成功用户的令牌（Token）");
        Map<String, Object> userMap = new HashMap<>();
        userMap.put("userId", one.getId());
        userMap.put("name", one.getName());
        // 生成令牌,需要注意点是需要把createToken设置为createToken(Map<String, Object> claims) Map集合类型的参数
        String token = tokenService.createToken(userMap);

        log.info("7.返回登录成功用户的信息");
        return LoginUserVo.builder().nickName(one.getName()).token(token).build();
    }

    /**
     * 查询老人家属
     *
     * @param id 老人家属主键
     * @return 老人家属
     *//*
    @Override
    public FamilyMember selectFamilyMemberById(Long id)
    {
        return getById(id);
    }

    *//**
     * 查询老人家属列表
     *
     * @param familyMember 老人家属
     * @return 老人家属
     *//*
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember)
    {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    *//**
     * 新增老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     *//*
    @Override
    public int insertFamilyMember(FamilyMember familyMember)
    {
        return save(familyMember) ? 1 : 0;
    }

    *//**
     * 修改老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     *//*
    @Override
    public int updateFamilyMember(FamilyMember familyMember)
    {
        return updateById(familyMember) ? 1 : 0;
    }

    *//**
     * 批量删除老人家属
     *
     * @param ids 需要删除的老人家属主键
     * @return 结果
     *//*
    @Override
    public int deleteFamilyMemberByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    *//**
     * 删除老人家属信息
     *
     * @param id 老人家属主键
     * @return 结果
     *//*
    @Override
    public int deleteFamilyMemberById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }*/
}
